package org.hxzon.tapestry5.components;

import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationDecorator;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.base.AbstractField;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.FormSupport;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.apache.tapestry5.upload.services.MultipartDecoder;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.slf4j.Logger;

public class Uploads extends AbstractField {
    public static final String MULTIPART_ENCTYPE = "multipart/form-data";

    @Parameter
    @Property
    private int filenum = 1;

    @Parameter(required = true, allowNull = false)
    private List<UploadedFile> values;

    //-------------------------
    @Inject
    private MultipartDecoder decoder;

    @Environmental
    private FormSupport formSupport;

    @Inject
    private ComponentResources resources;

//    @Inject
//    @Path("upload.js")
//    private Asset uploadScript;

    @Inject
    private Request request;

    @Environmental
    private JavaScriptSupport javaScriptSupport;

    @Inject
    private Logger logger;

    @BeginRender
    void begin(MarkupWriter writer) {

        String ctrlName = getControlName();
        formSupport.setEncodingType(MULTIPART_ENCTYPE);
        for (int i = 0; i < filenum; i++) {
            String clientId = getClientId();
            writer.element("input", "type", "file", "name", ctrlName + "_" + i, "id", clientId + "_" + i);
            resources.renderInformalParameters(writer);

            decorateInsideField();

            // TAPESTRY-2453
//            if (request.isXHR()) {
//                javaScriptSupport.importJavaScriptLibrary(uploadScript);
//                javaScriptSupport.addInitializerCall("injectedUpload", getClientId());
//            }
            writer.end();
            writer.element("br");
            writer.end();
        }
    }

    @Override
    protected void processSubmission(String elementName) {
        // logger.debug("element name:" + elementName + ",file name:" + filenum);
        String ctrlName = getControlName();
        for (int i = 0; i < filenum; i++) {
            try {
                UploadedFile uploaded = decoder.getFileUpload(ctrlName + "_" + i);
                if (uploaded == null || uploaded.getFileName() == null || uploaded.getFileName().length() == 0) {
                    continue;
                }
                values.add(uploaded);
                logger.debug("upload files:{}", uploaded.getFileName());
            } catch (Exception e) {
                logger.error("upload files exception", e);
            }
        }
    }

    Uploads injectDecorator(ValidationDecorator decorator) {
        setDecorator(decorator);

        return this;
    }

    Uploads injectRequest(Request request) {
        this.request = request;

        return this;
    }

    Uploads injectFormSupport(FormSupport formSupport) {
        // We have our copy ...
        this.formSupport = formSupport;

        // As does AbstractField
        setFormSupport(formSupport);

        return this;
    }
}
